/*
 * Copyright 2017 StreamSets Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.streamsets.datacollector.credential.streamsets;

import com.google.common.annotations.VisibleForTesting;
import com.streamsets.datacollector.credential.javakeystore.AbstractJavaKeyStoreCredentialStore;
import com.streamsets.lib.security.SshUtils;
import com.streamsets.pipeline.api.credential.CredentialStoreDef;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.List;

@CredentialStoreDef(label = "Streamsets Secrets")
public class StreamsetsCredentialStore extends AbstractJavaKeyStoreCredentialStore {
  private static final Logger LOG = LoggerFactory.getLogger(StreamsetsCredentialStore.class);

  static final String SSH_PRIVATE_KEY_SECRET = "sdc/defaultPrivateKey";
  static final String SSH_PRIVATE_KEY_PASSWORD_SECRET = "sdc/defaultPrivateKeyPassword"; //NOSONAR
  static final String SSH_PUBLIC_KEY_SECRET = "sdc/defaultPublicKey";

  @Override
  public List<ConfigIssue> init(Context context) {
    List<ConfigIssue> issues = super.init(context);
    if (issues.isEmpty()) {
      try {
        if (manager.getEntry(SSH_PRIVATE_KEY_SECRET) == null) {
          generateDefaultSshKeyInfo();
          LOG.info("Autogenerated default SDC SSH key info");
        }
      } catch (Exception ex) {
        issues.add(context.createConfigIssue(Errors.STREAMSETS_CRED_STORE_001, SSH_PRIVATE_KEY_PASSWORD_SECRET));
      }
    }
    return issues;
  }

  public void generateDefaultSshKeyInfo() {
    SshUtils.SshKeyInfoBean bean = createSshKeyInfo();
    store(Collections.singletonList(DEFAULT_SDC_GROUP), SSH_PRIVATE_KEY_SECRET, bean.getPrivateKey());
    store(Collections.singletonList(DEFAULT_SDC_GROUP), SSH_PRIVATE_KEY_PASSWORD_SECRET, bean.getPassword());
    store(Collections.singletonList(DEFAULT_SDC_GROUP), SSH_PUBLIC_KEY_SECRET, bean.getPublicKey());
  }

  @VisibleForTesting
  SshUtils.SshKeyInfoBean createSshKeyInfo() {
    return SshUtils.createSshKeyInfoBean(4096, "Default SDC SSH key info");
  }
}
